package cn.techfan.reactivekotlin

import org.reactivestreams.Publisher
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.builder.SpringApplicationBuilder
import org.springframework.cloud.netflix.eureka.EnableEurekaClient
import org.springframework.context.support.beans
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import org.springframework.web.reactive.function.server.ServerResponse
import org.springframework.web.reactive.function.server.body
import org.springframework.web.reactive.function.server.router
import reactor.core.publisher.toFlux

@EnableEurekaClient
@SpringBootApplication
class ReactiveKotlinApplication

fun main(args: Array<String>) {
    //runApplication<ReactiveApplication>(*args)
    SpringApplicationBuilder()
            .sources(ReactiveKotlinApplication::class.java)
            .initializers(beans {
                bean {
                    val customerRepository = ref<CustomerRepository>()
                    val customers: Publisher<Customer> = listOf("西兰花", "韭菜", "萝卜", "大蒜")
                            .toFlux()
                            .map { Customer(name = it) }
                            .flatMap { customerRepository.save(it) }
                    customerRepository
                            .deleteAll()
                            .thenMany(customers)
                            .thenMany(customerRepository.findAll())
                            .subscribe { println(it) }
                }
                bean {
                    router {
                        val customerRepository = ref<CustomerRepository>()
                        GET("/customers") { ServerResponse.ok().body(customerRepository.findAll()) }
                        GET("/customer/{id}") {
                            ServerResponse.ok()
                                    .body(customerRepository.findById(it.pathVariable("id")))
                        }
                    }
                }
            }).run(*args)
}

interface CustomerRepository : ReactiveMongoRepository<Customer, String>
@Document
data class Customer(@Id var id: String? = null, var name: String? = null)